import os
from datetime import datetime

import requests

# 网易云音乐API URL
search_url = 'https://music.163.com/api/cloudsearch/pc'
song_url = 'https://music.163.com/song/media/outer/url?id={}.mp3'

# 请求头，模拟浏览器访问
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}

# 搜索关键词参数
params = {
    's': '林俊杰',  # 搜索关键词
    'type': 1,  # 类型：1 单曲
    'offset': 0,
    'limit': 10  # 返回结果数量
}


def search_songs():
    try:
        response = requests.get(search_url, headers=headers, params=params)
        response.raise_for_status()  # 检查请求是否成功
        data = response.json()
        songs = data['result']['songs']
        return songs
    except requests.RequestException as e:
        print(f"请求错误: {e}")
    except (KeyError, IndexError) as e:
        print(f"数据解析错误: {e}")
    return []


def download_song(song_id, song_name, artist_name):
    try:
        url = song_url.format(song_id)
        response = requests.get(url, headers=headers)
        response.raise_for_status()  # 检查请求是否成功

        # 创建保存目录
        save_dir = 'music'
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)

        # 保存音乐文件
        file_path = os.path.join(save_dir, f"{song_name} - {artist_name}.mp3")
        with open(file_path, 'wb') as file:
            file.write(response.content)
        print(f"下载完成: {file_path}")
    except requests.RequestException as e:
        print(f"下载错误: {e}")


def main():
    songs = search_songs()
    if songs:
        print(f"获取时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        for song in songs:
            song_id = song['id']
            song_name = song['name']
            artist_name = song['ar'][0]['name']
            print(f"歌曲ID: {song_id}, 歌曲名: {song_name}, 歌手: {artist_name}")
            download_song(song_id, song_name, artist_name)


if __name__ == '__main__':
    main()
